package com.zhh.service.impl;

import com.zhh.common.ServerResponse;
import com.zhh.common.redis.RedisClient;
import com.zhh.dao.UserDao;
import com.zhh.jwt.JWTUtil;
import com.zhh.pojo.TbUser;
import com.zhh.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.RedisSystemException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private StringRedisTemplate redisClient;

    @Autowired
    private JWTUtil jwtUtil;

    @Override
    public Set<String> getRoles(String username) {
        List<String> list = userDao.getRoles(username);
        return new HashSet<>(list);
    }

    @Override
    public Set<String> getPermissions(String username) {
        List<String> list = userDao.getPermissions(username);
        return new HashSet<>(list);
    }

    @Override
    public TbUser getUserByname(String username) {

        return userDao.findbyUsername(username);
    }

    @Override
    public ServerResponse logout(String token) {
        if (StringUtils.isBlank(token)){
            return ServerResponse.createByErrorMessage("登出失败,用户不存在");
        }
        String username = jwtUtil.getUsername(token);
        if (StringUtils.isBlank(username)){
            return ServerResponse.createByErrorMessage("登出失败,用户不存在");
        }
        try {
            redisClient.delete("USER-TOKEN-"+username);
            return ServerResponse.createBySuccessMessage("登出成功");
        }catch (RedisSystemException e){
            return ServerResponse.createByErrorMessage(e.getMessage());
        }

    }
}
